import {Component, ViewChild, Renderer2} from '@angular/core';
import {Content, IonicPage, NavController, NavParams} from 'ionic-angular';
import {LoadingService} from "../../../services/common/loading.service";
import {ToastService} from "../../../services/common/toast.service";
import {InhousePerformanceProvider} from "../../../providers/perfomance/inhouse-performance/inhouse-performance.provider";
import * as moment from "moment";
import {InhouseModel,Organize} from '../../../model/pages/performance/inhouse-performance';

@IonicPage()
@Component({
    selector:'page-team-performance-inhouse',
    templateUrl:'team-performance-inhouse.html',
    providers:[
        LoadingService,
        InhousePerformanceProvider,
        ToastService
    ]
})

export class TeamPerformanceInhousePage {
    //组织架构数据
    public organizeData:Array<Organize>=[];
    //筛选条件
    public filter={
        code:'', //默认地区显示，必填
        type:'D', //时间类型，必填
        time:'', //筛选时间
        cacheTime:'' //保存DTD时间
    };
    //内勤数据
    public inhouseData:any={};
    // 时间插件--年月日汉字填充
    private pickerOptions = {
        cssClass: 'filter-add-picker'
    };
    // picker当前最大时间节点
    private maxDateYear = Number(moment(new Date()).format('YYYY'));

    constructor(
        private navCtrl:NavController,
        private navParams:NavParams,
        private load:LoadingService,
        private toast:ToastService,
        private renderer:Renderer2,
        private inhousePerformanceProvider:InhousePerformanceProvider
    ){
        //初始化组织架构数据
        this.getorganizeData();
    }

    /**
     * 向datatpicker添加年度顺序排列数据：[2010,2011,2012...2100]
     */
    getYearList(start: number, end: number = this.maxDateYear) {
        let years = [];
        if (typeof start == 'number' && typeof end == 'number' && start && end) {
            for (let y = start; y <= end; y++) {
                years.push(y)
            }
        } else {
            for (let y =start; y <= end; y++) {
                years.push(y)
            }
        }
        return years
    }

    /**
     * 修正插件ion-mulit-picker跳闪
     */
    patch(arr) {
        let firstList:Array<any>=[],
            secondList:Array<any>=[],
            thirdList:Array<any>=[];

        arr.forEach(item=>{
            if(item.name === 'first') firstList = item.options;
            else if(item.name === 'second') secondList = item.options;
            else thirdList = item.options;
        });

        firstList.forEach(item=>{
            if(item.text === '全国') {
                secondList.unshift({text:'',value:'',parentVal:item.value});
                thirdList.unshift({text:'',value:'',parentVal:item.value});
            }
        });

        secondList.forEach(item=>{
            if(item.text === '全部') {
                thirdList.unshift({text:'',value:'',parentVal:item.value});
            }
        });
        console.log(arr);
        return arr;
    }

    /**
     * 获取组织架构数据
     */
    getorganizeData(){
        this.load.showLoading();
        this.inhousePerformanceProvider.getorganizeData().subscribe(data=>{
            this.organizeData = this.patch(data);
           // this.load.dismissLoading();
            this.initFilter();
        },error=>{
            this.load.dismissLoading();
        });
    }

    /**
     * 获取内勤数据
     */
    getInhouseData(isShowing=1) {
        if(isShowing){
            this.load.showLoading();
        }
        this.inhousePerformanceProvider.getInhouseData(this.filter).subscribe(data=>{
            if(this.filter.type === 'D') {
                let y=data.date.slice(0,4);
                let m=data.date.slice(4,6);
                let d=data.date.slice(-2);
                this.filter.time = y+'-'+m+'-'+d;
                this.filter.cacheTime = this.filter.time;
            }
            this.inhouseData = data;
            this.load.dismissLoading();
        },error=>{
            this.load.dismissLoading();
        });
    }

    /**
     * 切换筛选时间类型
     */
    changeDateType(type:string) {
        if(type !== 'D'){
            this.filter.time = moment(new Date()).format('YYYY-MM');
        }else{
            this.filter.time = this.filter.cacheTime;
        }
        this.filter.type = type;
    }

    /**
     * 初始化filter
     */
    initFilter() {
        let firstList:any={},
            secondList:any={},
            thirdList:any={},
            firstCode:string='null',
            secondCode:string='null',
            thirdCode:string='null';
        //初始化省，市，区
        this.organizeData.forEach(item=>{
            if(item.name === 'first') firstList=item;
            else if(item.name === 'second') secondList=item;
            else thirdList=item;
        });
        //判断 0：唯一；1：全国/全部；2：请选择
        let choice = (list):{code:string,done:number}=>{
            if(list.options.length === 1){
                return {code:list.options[0].value,done:0};
            }else{
                let flag:boolean=false,code:string='null';
                list.options.forEach(item=>{
                    if(item.text === '全国' || item.text === '全部'){
                        flag = true;
                        code = item.value;
                    }
                });
                return flag ? {code,done:1} : {code,done:2};
            }
        };
        //发请求
        let go = ():void=>{
            this.filter.code = [firstCode,secondCode,thirdCode].join(' ');
            console.log('GO',this.filter.code);
            this.getInhouseData(0);
        }
        //赋值code
        let setCode = (name:string,code:string,ok?:boolean)=>{
            switch (name){
                case 'first':
                    firstCode = code;
                    break;
                case 'second':
                    secondCode = code;
                    break;
                default:
                    thirdCode = code;
            };

            if(ok) go();
        };
        //处理不同情况
        let handler = (list)=>{
            let res = choice(list),
                flag=false;
            switch (res.done){
                case 0:
                    flag = true;
                    setCode(list.name,res.code);  //继续判断
                    break;
                case 1:
                    setCode(list.name,res.code,true);  //请求数据
                    break;
                default:
                    this.filter.code = '';  //请选择
            };
            return flag;
        }
        //进行循环判断
        for(let i = 0,arr = this.organizeData;i<arr.length;i++){
            if(!handler(arr[i])) return;
        }

        go();// 说明是一个区
    }

    /**
     * 添加样式ion-picker-cmp
     */
    addAttri() {
        console.log(this.filter.code);
        setTimeout(()=>{
            let el=document.getElementsByTagName('ion-picker-cmp')[0];
            this.renderer.setAttribute(el,'inhouse','');
        },0)
    }

    /**
     * 返回
     * @param ev
     */
    backButtonClick(ev) {
        ev.preventDefault();
        ev.stopPropagation();
        this.navCtrl && this.navCtrl.pop(null, null);
    }
}

